<template lang="pug">
.cp-manage-materiel-popup
  el-dialog.ml-dialog(
    :title="title",
    :visible="visible",
    @close="closeDialog",
    :close-on-click-modal="viewStatus",
    width="80%")
    el-tabs.dg-tabs(v-model="activeTabIndex", @tab-click="handlePopTab")
      el-tab-pane(label="基本", name="0")
      el-tab-pane(label="库存", name="1")
      el-tab-pane(label="采购", name="2")
      el-tab-pane(label="销售", name="3")
      //- el-tab-pane(label="生产", name="4")
    .c-pop-tab.tab-base(v-show="tabShows[0]")
      .bs-title 基本信息
      .bs-content.ml-pop-content
        el-form.ml-pop-form(:model="popupObj", :inline="true", :rules="rules", ref="popupObj", label-width="100px")
          el-row(:gutter="20")
            el-col(:span="8")
              el-form-item(label="物料编码", prop="skuId")
                el-tooltip(placement="top", :content="popupObj.skuId", :disabled="!popupObj.skuId")
                  el-input(v-model="popupObj.skuId", placeholder="自动生成", disabled)
            el-col(:span="8")
              el-form-item(label="物料类别", prop="category")
                el-select(:disabled="viewStatus", v-model="popupObj.category", placeholder="请选择")
                  el-option(
                    v-for="(item, index) in cateGorySelect",
                    :key="index", :label="item.name",
                    :value="item.value")
            el-col(:span="8")
              el-form-item(label="需求一级部门")
                el-select(:disabled="viewStatus", v-model="popupObj.deptLevel1", @change="changeOneLevelDept", placeholder="请选择")
                  el-option(
                    v-for="(item, index) in deptLevel1Select",
                    :key="index", :label="item.name",
                    :value="item.value")
          el-row(:gutter="20")
            el-col(:span="8")
              el-form-item(label="名称", prop="name")
                el-input(:disabled="viewStatus", v-model="popupObj.name", placeholder="")
            el-col(:span="8")
              el-form-item(label="物料属性", prop="property")
                el-select(:disabled="viewStatus", v-model="popupObj.property", placeholder="请选择")
                  el-option(
                    v-for="(item, index) in propertySelect",
                    :key="index", :label="item.name",
                    :value="item.value")
            el-col(:span="8")
              el-form-item(label="需求二级部门")
                el-select(:disabled="viewStatus", v-model="popupObj.deptLevel2", placeholder="请选择")
                  el-option(
                    v-for="(item, index) in deptLevel2Select",
                    :key="index", :label="item.name",
                    :value="item.value")
          el-row(:gutter="20")
            el-col(:span="8")
              el-form-item(label="型号规格", prop="specification")
                el-input(:disabled="viewStatus", v-model="popupObj.specification", placeholder="")
            el-col(:span="8")
              el-form-item(label="物料分级", prop="skuGrade")
                el-select(:disabled="viewStatus", v-model="popupObj.skuGrade", placeholder="请选择")
                  el-option(
                    v-for="(item, index) in skuGradeSelect",
                    :key="index", :label="item.name",
                    :value="item.value")
            el-col(:span="8")
              el-form-item(label="创建人", prop="createUser")
                el-select(disabled, v-model="popupObj.createUser", placeholder="请选择")
                  el-option(
                    v-for="(item, index) in createUserSelect",
                    :key="index", :label="item.name",
                    :value="item.value")
          el-row(:gutter="20")
            el-col(:span="8")
              el-form-item(label="制造商")
                el-select(:disabled="viewStatus", v-model="popupObj.manufacturer", placeholder="请选择")
                  el-option(
                    v-for="(item, index) in manufacturerSelect",
                    :key="index", :label="item.name",
                    :value="item.value")
            el-col(:span="8")
              el-form-item(label="自定义分类")
                .custom-category
                  el-input(disabled, v-model="popupObj.customCategoryName", placeholder="自动编码时启用")
                  el-button(:disabled="viewStatus || !!popupObj.skuId", @click="showCustomPopup") 选择
            el-col(:span="8")
              el-form-item(label="状态", prop="status")
                el-select(:disabled="viewStatus", v-model="popupObj.status", placeholder="请选择")
                  el-option(
                    v-for="(item, index) in statusSelect",
                    :key="index", :label="item.name",
                    :value="item.value")
          el-row(:gutter="20")
            el-col(:span="8")
              el-form-item(label="BOM版本")
                el-input(:disabled="viewStatus", v-model="popupObj.bomVersion", placeholder="")
            el-col(:span="8")
              el-form-item(label="基本单位", prop="skuUnit")
                el-select(:disabled="viewStatus", v-model="popupObj.skuUnit", placeholder="请选择")
                  el-option(
                    v-for="(item, index) in skuUnitSelect",
                    :key="index", :label="item.name",
                    :value="item.value")
            el-col(:span="8")
              el-form-item(label="备注")
                el-input(:disabled="viewStatus", v-model="popupObj.remark", placeholder="")
          el-row(:gutter="20")
            el-col(:span="8")
              el-form-item(label="描述")
                el-input(:disabled="viewStatus", v-model="popupObj.description", placeholder="")
            el-col(:span="8")
              el-form-item(label="原厂物料编号")
                el-input(:disabled="viewStatus", v-model="popupObj.originalIdentity", placeholder="")
            el-col(:span="8")
              el-form-item(label="原厂型号规格")
                el-input(:disabled="viewStatus", v-model="popupObj.originalSpecification", placeholder="")
          el-row.ml-upload-img
            span.upload-label 图片
            el-upload.upload-block(
              action="https://jsonplaceholder.typicode.com/posts/"
              list-type="picture-card",
              :file-list="popupObj.picture",
              :on-preview="handlePicCardPreview",
              :on-success="handlePicUploadSucc"
              :limit="1"
              :disabled="viewStatus"
              :on-exceed="handlePicExceed"
              :on-remove="handlePicRemove")
              i.el-icon-plus
          .ml-register
            .rr-title.ml-pop-title 注册
            .rr-content.ml-pop-content
              p.ml-p
                el-checkbox(true-label="1", false-label="0", :disabled="viewStatus", v-model="popupObj.isCriticalPart") 是否安全关键件（依据医疗器械安全标准定义的器件）
          .ml-aftersale
            .as-title.ml-pop-title 售后
            .as-content.ml-pop-content
              p.ml-p
                el-checkbox(true-label="1", false-label="0", :disabled="viewStatus", v-model="popupObj.isSparePart") 是否备件
          .ml-check
            .ck-title.ml-pop-title 检验
            .ck-content.ml-pop-content
              el-row(:gutter="20")
                el-col(:span="6")
                  el-checkbox(true-label="1", false-label="0", :disabled="viewStatus", v-model="popupObj.inspectingMaterial") 来料检验
                el-col(:span="6")
                  el-checkbox(true-label="1", false-label="0", :disabled="viewStatus", v-model="popupObj.inspectingProcess") 过程检验
                el-col(:span="6")
                  el-checkbox(true-label="1", false-label="0", :disabled="viewStatus", v-model="popupObj.inspectingProduct") 成品检验
              p.tip-info 注：来料检验开启后，入库时需要填写检验单号。成品检验仅适用于物料类别为半成品或者成品的物料。
          .ml-control
            .ct-title.ml-pop-title 控制
            .ct-content.ml-pop-content
              el-row(:gutter="20")
                el-col(:span="6")
                  el-checkbox(true-label="1", false-label="0", :disabled="viewStatus", v-model="popupObj.allowingProcurement") 允许采购
                el-col(:span="6")
                  el-checkbox(true-label="1", false-label="0", :disabled="viewStatus", v-model="popupObj.allowingOutsourcing") 允许委外
                el-col(:span="6")
                  el-checkbox(true-label="1", false-label="0", :disabled="viewStatus", v-model="popupObj.allowingProduction") 允许生产
                el-col(:span="6")
                  el-checkbox(true-label="1", false-label="0", :disabled="viewStatus", v-model="popupObj.allowingSales") 允许销售
    .c-pop-tab.tab-store(v-show="tabShows[1]")
      p.c-store-title.cst-title 存储
      .c-store-content.cst-content
        el-form.ml-pop-form(:inline="true", label-width="100px")
          el-row(:gutter="20")
            el-col(:span="8")
              el-form-item(label="默认仓库")
                el-select(:disabled="viewStatus", v-model="popupObj.inventoryStorehouseId", placeholder="请选择")
                  el-option(
                    v-for="(item, index) in storeSelect",
                    :key="index", :label="item.name",
                    :value="item.value")
            el-col(:span="8")
              el-form-item(label="库存单位")
                el-select(:disabled="viewStatus", v-model="popupObj.inventoryUnit", placeholder="请选择")
                  el-option(
                    v-for="(item, index) in skuUnitSelect",
                    :key="index", :label="item.name",
                    :value="item.value")
            el-col(:span="8")
              el-form-item(label="单位换算：")
                p.height32
                  span  一单位=
                  el-input(:disabled="viewStatus", v-model="popupObj.inventoryUnitRate", style="width: 60px;")
                  span  基本单位
      p.c-store-title.cma-title 管理
      .c-store-content.cma-content
        el-form.ml-pop-form(:inline="true", label-width="100px")
          el-row(:gutter="20")
            el-col(:span="8")
              el-checkbox(true-label="1", false-label="0", :disabled="viewStatus", v-model="popupObj.batchNumUsing") 启用批号管理
            el-col(:span="8")
              el-form-item(label="批号规则")
                el-select(:disabled="viewStatus || popupObj.batchNumUsing === '0'", v-model="popupObj.batchNumFlag", placeholder="请选择")
                  el-option(label="自动生成", value="1")
                  el-option(label="手动生成", value="0")
          el-row(:gutter="20")
            el-col(:span="8")
              el-checkbox(true-label="1", false-label="0", :disabled="viewStatus", v-model="popupObj.seqNumUsing") 启用序列号管理
            el-col(:span="8")
              el-form-item(label="序列号规则")
                el-select(:disabled="viewStatus || popupObj.seqNumUsing === '0'", v-model="popupObj.seqNumFlag", placeholder="请选择")
                  el-option(label="自动生成", value="1")
                  el-option(label="手动生成", value="0")
          el-row(:gutter="20")
            el-col(:span="8")
              el-checkbox(true-label="1", false-label="0", :disabled="viewStatus", v-model="popupObj.validitySpanUsing") 启用保质期管理
            el-col(:span="8")
              el-form-item(label="保质期")
                el-input(:disabled="viewStatus || popupObj.validitySpanUsing === '0'", v-model="popupObj.validitySpan", style="width: 90px")
                el-select(:disabled="viewStatus || popupObj.validitySpanUsing === '0'", v-model="popupObj.validitySpanUnit", placeholder="请选择" style="width: calc(100% - 90px)")
                  el-option(label="天", :value="1")
                  el-option(label="月", :value="30")
                  el-option(label="年", :value="365")
          el-row(:gutter="20")
            el-col(:span="8")
              el-checkbox(true-label="1", false-label="0", :disabled="viewStatus", v-model="popupObj.bomManagementUsing") 启用BOM版本管理
            el-col(:span="8")
              el-form-item(label="BOM版本")
                el-select(:disabled="viewStatus || popupObj.bomManagementUsing === '0'", v-model="popupObj.bomManagementFlag", placeholder="请选择")
                  el-option(label="自动生成", value="1")
                  el-option(label="手动生成", value="0")
      p.c-store-title.cwa-title 预警
      .c-store-content.cwa-content
        el-row
          el-col(:span="8")
            el-checkbox(true-label="1", false-label="0", :disabled="viewStatus", v-model="popupObj.qalertUsing") 启用数量预警
        el-row(:gutter="20")
          el-col(:span="8")
            p.height32(style="padding-left: 32px;")
              el-radio(:disabled="viewStatus || popupObj.qalertUsing === '0'", v-model="popupObj.qalertStorehouseMode", label="0") 使用所有仓库设置：
          el-col(:span="8")
            span(style="padding-right: 10px;") 上限
            el-input(:disabled="viewStatus || popupObj.qalertStorehouseMode !== '0'", v-model="popupObj.allStorehouseMaxNum", style="width: 100px")
          el-col(:span="8")
            span(style="padding-right: 10px;") 下限
            el-input(:disabled="viewStatus || popupObj.qalertStorehouseMode !== '0'", v-model="popupObj.allStorehouseMinNum", style="width: 100px")
        el-row
          el-col(:span="8")
            p.height32(style="padding-left: 32px;")
              el-radio(:disabled="viewStatus || popupObj.qalertUsing === '0'", v-model="popupObj.qalertStorehouseMode", label="1") 使用单个仓库设置：
            .init-btn(v-show="!viewStatus && popupObj.qalertStorehouseMode === '1'", v-if="!popupObj.qalerts || !popupObj.qalerts.length")
              el-button(type="primary", @click="initQalerts", size="mini") 初始化行
          el-col(:span="16")
            .ml-view-table
              el-table(
                :data="popupObj.qalerts",
                highlight-current-row
                height="200px"
                size="mini")
                el-table-column(align="center", show-overflow-tooltip, prop="storeHouse", label="仓库")
                  template(slot-scope="scope")
                    el-select(v-show="scope.row.canEdit", v-model="scope.row.storeHouse", placeholder="请选择")
                      el-option(
                        v-for="(item, index) in storeSelect",
                        :key="index", :label="item.name",
                        :value="item.value")
                    span(v-show="!scope.row.canEdit") {{scope.row.storeHouse | compare-list(storeSelect)}}
                el-table-column(align="center", show-overflow-tooltip, prop="upperLimit", label="上限")
                  template(slot-scope="scope")
                    el-input(v-model="scope.row.upperLimit", v-show="scope.row.canEdit")
                    span(v-text="scope.row.upperLimit", v-show="!scope.row.canEdit")
                el-table-column(align="center", show-overflow-tooltip, prop="lowerLimit", label="下限")
                  template(slot-scope="scope")
                    el-input(v-model="scope.row.lowerLimit", v-show="scope.row.canEdit")
                    span(v-text="scope.row.lowerLimit", v-show="!scope.row.canEdit")
                el-table-column(align="center", label="操作", min-width="104px", v-if="!viewStatus")
                  template(slot-scope="scope")
                    div(v-show="!scope.row.canEdit")
                      i.icon-act.el-icon-edit(@click="editQalerts(scope.$index, scope.row)")
                      i.icon-act.el-icon-plus(@click="addQalerts(scope.$index, scope.row)")
                      i.icon-act.el-icon-delete(@click="deleteQalerts(scope.$index, scope.row)")
                    div(v-show="scope.row.canEdit")
                      i.icon-act.el-icon-check(@click="saveEditQalerts(scope.$index, scope.row)")
                      i.icon-act.el-icon-close(@click="cancelEditQalerts(scope.$index, scope.row)")
        el-row
          el-col(:span="8")
            p.height32
              el-checkbox(true-label="1", false-label="0", :disabled="viewStatus", v-model="popupObj.valertUsing") 启用有效期预警
          el-col(:span="8")
            span 提前预警天数
            el-input(:disabled="viewStatus || popupObj.valertUsing === '0'", v-model="popupObj.valertDays", class="v-alert-day")
    .c-pop-tab.tab-purchase(v-show="tabShows[2]")
      .ml-pe-purchase
        p.c-purchase-title(v-text="popupObj.property != 2 ? '采购' : '委外'")
        .c-purchase-content.pe-content
          el-form.ml-pop-form(:inline="true", label-width="100px")
            el-row(:gutter="20")
              el-col(:span="8")
                el-form-item(label="采购单位")
                  el-select(:disabled="viewStatus", v-model="popupObj.proUnit", placeholder="请选择")
                    el-option(
                      v-for="(item, index) in skuUnitSelect",
                      :key="index", :label="item.name",
                      :value="item.value")
              el-col(:span="8")
                el-form-item(label="单位换算：")
                  p.height32
                    span  一单位=
                    el-input(:disabled="viewStatus", v-model="popupObj.proUnitRate", style="width: 60px;")
                    span  基本单位
            el-row(:gutter="20")
              el-col(:span="8")
                el-form-item(label="采购一级部门")
                  el-select(:disabled="viewStatus", v-model="popupObj.proDeptLevel1", @change="changeProOneLevelDept", placeholder="请选择")
                    el-option(
                      v-for="(item, index) in proDeptLevel1Select",
                      :key="index", :label="item.name",
                      :value="item.value")
              el-col(:span="8")
                el-form-item(label="采购二级部门")
                  el-select(:disabled="viewStatus", v-model="popupObj.proDeptLevel2", @change="changeProTwoLevelDept", placeholder="请选择")
                    el-option(
                      v-for="(item, index) in proDeptLevel2Select",
                      :key="index", :label="item.name",
                      :value="item.value")
              el-col(:span="8")
                el-form-item(label="采购员")
                  el-select(
                    v-show="!viewStatus",
                    :disabled="viewStatus",
                    v-model="popupObj.procurers",
                    multiple,
                    collapse-tags,
                    placeholder="请选择")
                    el-option(
                      v-for="(item, index) in procurerSelect",
                      :key="index", :label="item.name",
                      :value="item.value")
                  el-tooltip(
                    v-show="viewStatus",
                    placement="top",
                    :content="procurersName",
                    :disabled="!procurersName")
                    el-input(v-model="procurersName", placeholder="请选择", disabled)
            el-row(:gutter="20")
              el-col(:span="8")
                el-form-item(label="默认供应商")
                  el-select(:disabled="viewStatus || popupObj.usingSpyMgm==1", v-model="popupObj.vendorId", placeholder="请选择")
                    el-option(
                      v-for="(item, index) in vendorSelect",
                      :key="index", :label="item.name",
                      :value="item.value")
              el-col(:span="8")
                el-form-item(label="包装信息")
                  el-input(:disabled="viewStatus", v-model="popupObj.pkgInfo")
      .ml-pe-control
        p.c-purchase-title 控制
        .c-purchase-content.cl-content
          el-form.ml-pop-form(:inline="true", label-width="100px")
            el-row(:gutter="20")
              el-col(:span="8")
                el-form-item(label="最小起订量")
                  el-input(:disabled="viewStatus", v-model="popupObj.minOrderPro", placeholder="")
              el-col(:span="8")
                el-form-item(label="最大起订量")
                  el-input(:disabled="viewStatus", v-model="popupObj.maxOrderPro", placeholder="")
              el-col(:span="8")
                el-form-item(label="批量增量")
                  el-input(:disabled="viewStatus", v-model="popupObj.batchInc", placeholder="")
            el-row(:gutter="20")
              el-col(:span="8")
                p(style="height: 24px; line-height: 24px")
                  el-checkbox(true-label="1", false-label="0", :disabled="viewStatus", v-model="popupObj.usingSpyMgm") 启用货源控制
                  span.init-link(v-show="!viewStatus && popupObj.usingSpyMgm === '1'", v-if="!popupObj.skuProcurementControls || !popupObj.skuProcurementControls.length")
                    a(@click="initVendor") 初始化行
          .ml-view-table
            el-table(
              :data="popupObj.skuProcurementControls",
              highlight-current-row
              height="200px"
              size="mini")
              el-table-column(align="center", show-overflow-tooltip, prop="vendorId", label="供应商")
                template(slot-scope="scope")
                  el-select(v-show="scope.row.canEdit", v-model="scope.row.vendorId")
                    el-option(
                      v-for="(item, index) in supplySelect",
                      :key="index", :label="item.name",
                      :value="item.value")
                  span(v-show="!scope.row.canEdit") {{scope.row.vendorId | compare-list(supplySelect)}}
              el-table-column(align="center", show-overflow-tooltip, prop="unitPrice", label="默认单价")
                template(slot-scope="scope")
                  el-input(v-model="scope.row.unitPrice", v-show="scope.row.canEdit")
                  span(v-text="scope.row.unitPrice", v-show="!scope.row.canEdit")
              el-table-column(align="center", show-overflow-tooltip, prop="currency", label="币种")
                template(slot-scope="scope")
                  el-select(v-show="scope.row.canEdit", v-model="scope.row.currency", placeholder="请选择")
                    el-option(
                      v-for="(item, index) in currencySelect",
                      :key="index", :label="item.name",
                      :value="item.value")
                  span(v-show="!scope.row.canEdit") {{scope.row.currency | compare-list(currencySelect)}}
              el-table-column(align="center", show-overflow-tooltip, prop="defaultFlag", label="是否默认")
                template(slot-scope="scope")
                  el-select(v-show="scope.row.canEdit", v-model="scope.row.defaultFlag", placeholder="请选择")
                    el-option(
                      v-for="(item, index) in defaultFlagSelect",
                      :key="index", :label="item.name",
                      :value="item.value")
                  span(v-show="!scope.row.canEdit") {{scope.row.defaultFlag | compare-list(defaultFlagSelect)}}
              el-table-column(align="center", show-overflow-tooltip, prop="leadTime", label="供货周期(天)")
                template(slot-scope="scope")
                  el-input(v-model="scope.row.leadTime", v-show="scope.row.canEdit")
                  span(v-text="scope.row.leadTime", v-show="!scope.row.canEdit")
              el-table-column(align="center", label="操作", min-width="104px", v-if="!viewStatus")
                template(slot-scope="scope")
                  div(v-show="!scope.row.canEdit")
                    i.icon-act.el-icon-edit(@click="editVendor(scope.$index, scope.row)")
                    i.icon-act.el-icon-plus(@click="addVendor(scope.$index, scope.row)")
                    i.icon-act.el-icon-delete(@click="deleteVendor(scope.$index, scope.row)")
                  div(v-show="scope.row.canEdit")
                    i.icon-act.el-icon-check(@click="saveEditVendor(scope.$index, scope.row)")
                    i.icon-act.el-icon-close(@click="cancelEditVendor(scope.$index, scope.row)")
          p.tip-info 注1：默认单价是指采购时自动填写的单价，用户可以修改，并非价格控制。
    .c-pop-tab.tab-sales(v-show="tabShows[3]")
      p.c-sales-title(style="margin-bottom: 8px") 销售
      .c-sales-content.pe-content
        el-form.ml-pop-form(:inline="true", label-width="100px")
          el-row(:gutter="20")
            el-col(:span="8")
              el-form-item(label="销售单位")
                el-select(:disabled="viewStatus", v-model="popupObj.sellUnit", placeholder="请选择")
                  el-option(
                    v-for="(item, index) in skuUnitSelect",
                    :key="index", :label="item.name",
                    :value="item.value")
            el-col(:span="8")
              el-form-item(label="单位换算：")
                p.height32
                  span  一单位=
                  el-input(:disabled="viewStatus", v-model="popupObj.sellUnitRate", style="width: 60px;")
                  span  基本单位
          el-row(:gutter="20")
            el-col(:span="8")
              el-form-item(label="销售单价")
                el-input(:disabled="viewStatus", v-model="popupObj.price")
            el-col(:span="8")
              el-form-item(label="币种")
                el-select(:disabled="viewStatus", v-model="popupObj.currency", placeholder="请选择")
                  el-option(
                    v-for="(item, index) in currencySelect",
                    :key="index", :label="item.name",
                    :value="item.value")
          el-row(:gutter="20")
            el-col(:span="8")
              el-form-item(label="最小起订量")
                el-input(:disabled="viewStatus", v-model="popupObj.minOrder")
            el-col(:span="8")
              el-form-item(label="超发上限")
                el-input(:disabled="viewStatus", v-model="popupObj.maxOverissuance")
    .c-pop-tab.tab-prod(v-show="tabShows[4]")
      p.c-prod-title(style="margin-bottom: 8px") 生产
      .c-prod-content.ct-content
        el-form.ml-pop-form(:inline="true", label-width="100px")
          el-row(:gutter="20")
            el-col(:span="8")
              el-form-item(label="发料单位")
                el-select(:disabled="viewStatus", v-model="popupObj.prdUnit", placeholder="请选择")
                  el-option(
                    v-for="(item, index) in skuUnitSelect",
                    :key="index", :label="item.name",
                    :value="item.value")
            el-col(:span="8")
              el-form-item(label="单位换算：")
                p.height32
                  span  一单位=
                  el-input(:disabled="viewStatus", v-model="popupObj.prdUnitRate", style="width: 60px;")
                  span  基本单位
          el-row(:gutter="20")
            el-col(:span="8")
              el-form-item(label="发料仓库")
                el-select(:disabled="viewStatus", v-model="popupObj.prdStorehouseId", placeholder="请选择")
                  el-option(
                    v-for="(item, index) in storeSelect",
                    :key="index", :label="item.name",
                    :value="item.value")
            el-col(:span="8")
              el-form-item(label="最小发料数量")
                el-input(:disabled="viewStatus", v-model="popupObj.minIssuance")
          el-row(:gutter="20")
            el-col(:span="8")
              el-form-item(label="发料方式")
                el-select(:disabled="viewStatus", v-model="popupObj.allowingOverissuance", placeholder="请选择")
                  el-option(
                    v-for="(item, index) in allowOverSelect",
                    :key="index", :label="item.name",
                    :value="item.value")
            el-col(:span="8")
              el-form-item(label="超发比例")
                el-input(:disabled="viewStatus", v-model="popupObj.overissuanceRate")
    .dialog-footer(slot="footer")
      el-button(type="primary", plain, @click="closeDialog") 取消
      el-button(type="primary", style="margin-left: 40px;", @click="saveMateriel", v-text="viewStatus ? '确定': '保存'", :disabled="saving")
  el-dialog(:visible.sync="showImgDialog", append-to-body)
    img(width="100%", :src="showImageUrl", alt="")
  custom-type(
    :visible="showCustomType",
    :data="popupObj.customCategory",
    @submit="handleSelect",
    @close="showCustomType = false")
</template>

<script>
import { mapGetters } from 'vuex';
import ComApi from '@/api/common';
import ManApi from '@/api/manage';
import customType from './customType';

const numReg = /^\d+$/;

// 使自动生成的单号为空时不提示
const validValue = (rule, value, callback) => {
  callback();
};

export default {
  name: 'invmaterielpopup',
  components: {
    customType
  },
  props: {
    title: String,
    visible: Boolean,
    viewStatus: Boolean,
    parentData: Object
  },
  data() {
    return {
      // 图片上传
      showImgDialog: false,
      showImageUrl: '',
      // popup tab切换
      activeTabIndex: '0',
      tabShows: [true, false, false, false, false],
      // popup dialog
      saving: false,
      // 基础
      popupObj: {
        status: '0',
        picture: [],
        qalerts: [],
        procurers: [],
        skuProcurementControls: []
      },
      // 备份列表
      skuProcurementControlsBC: [],
      qalertsBC: [],
      // 显示自定义分类
      showCustomType: false,
      // 下拉选项
      cateGorySelect: [],
      propertySelect: [],
      skuGradeSelect: [],
      deptLevel1Select: [],
      deptLevel2Select: [],
      createUserSelect: [],
      statusSelect: [{ name: '启用', value: '0' }, { name: '禁用', value: '1' }],
      manufacturerSelect: [],
      skuUnitSelect: [],
      storeSelect: [],
      vendorSelect: [],
      proDeptLevel1Select: [],
      proDeptLevel2Select: [],
      procurerSelect: [],
      currencySelect: [],
      allowOverSelect: [],
      defaultFlagSelect: [{ name: '是', value: '1' }, { name: '否', value: '0' }],
      rules: {
        skuId: [
          { required: true, message: '请输入物料编码', trigger: 'blur', validator: validValue }
        ],
        category: [
          { required: true, message: '请选择物料类别', trigger: 'change' }
        ],
        name: [
          { required: true, message: '请选择名称', trigger: 'change' }
        ],
        property: [
          { required: true, message: '请选择物料属性', trigger: 'change' }
        ],
        specification: [
          { required: true, message: '请选择型号规格', trigger: 'change' }
        ],
        skuGrade: [
          { required: true, message: '请选择物料分级', trigger: 'change' }
        ],
        createUser: [
          { required: true, message: '请选择创建人', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        skuUnit: [
          { required: true, message: '请选择基本单位', trigger: 'change' }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(['employeeId', 'supplySelect']),
    procurersName () {
      if (this.popupObj.procurers && this.procurerSelect.length) {
        const arr = [];
        this.procurerSelect.forEach((item) => {
          if (this.popupObj.procurers.indexOf(item.value) > -1) {
            arr.push(item.name);
          }
        });
        return arr.join(',');
      } else {
        return null;
      }
    }
  },
  methods: {
    // 移除表单的校验结果
    clearValidate () {
      if (this.$refs.popupObj) {
        this.$refs.popupObj.clearValidate();
      }
    },
    closeDialog () {
      this.clearValidate();
      this.$emit('close');
    },
    // 显示自定义分类
    showCustomPopup () {
      if (!this.viewStatus && !this.popupObj.skuId) {
        this.showCustomType = true;
      }
    },
    // 选择自定义分类
    handleSelect (data) {
      if (data) {
        this.popupObj.customCategory = data.id;
        this.popupObj.customCategoryName = data.name;
      } else {
        this.$set(this.popupObj, 'customCategory', null);
        this.$set(this.popupObj, 'customCategoryName', null);
      }
      this.showCustomType = false;
    },
    initUploadImag (imgList) {
      if (!this.popupObj.picRecords) {
        this.popupObj.picRecords = [];
      }
      for (const img of imgList) {
        this.popupObj.picRecords.push(img.url);
      }
    },
    // 初始化请求结果
    dealDetail (result) {
      // 兼容图片列表
      if (result.picture && typeof result.picture === 'string') {
        this.popupObj.picture = [{ name: '', url: result.picture }];
      } else {
        this.popupObj.picture = [];
      }
      // 兼容采购员
      if (result.procurers && typeof result.procurers === 'string') {
        this.popupObj.procurers = result.procurers.split(',');
      } else {
        this.popupObj.procurers = [];
      }
    },
    // 处理提交的数据
    dealParams () {
      const params = { ...this.popupObj };
      // 兼容图片列表
      if (this.popupObj.picture.length) {
        params.picture = this.popupObj.picture[0].url;
      } else {
        params.picture = null;
      }
      // 兼容采购员
      if (this.popupObj.procurers.length) {
        params.procurers = this.popupObj.procurers.join(',');
      } else {
        params.procurers = null;
      }
      return params;
    },
    // 校验数据
    validData() {
      let canSave = true;
      const {
        qalertUsing,
        qalertStorehouseMode,
        allStorehouseMaxNum,
        allStorehouseMinNum,
        qalerts,
        valertUsing,
        valertDays
      } = this.popupObj;
      if (qalertUsing === '1' && !qalertStorehouseMode) {
        // 启用数量预警，未选择仓库设置
        this.$message.error('请选择仓库设置');
        return false;
      }
      if (qalertStorehouseMode === '0') {
        // 所有仓库设置
        if ((!allStorehouseMaxNum && allStorehouseMaxNum !== 0) || (!allStorehouseMinNum && allStorehouseMinNum !== 0)) {
          this.$message.error('请输入仓库设置上限下限');
          return false;
        }
        if (!numReg.test(allStorehouseMaxNum) || !numReg.test(allStorehouseMinNum)) {
          this.$message.error('仓库设置上限下限输入错误');
          return false;
        }
        if (Number(allStorehouseMaxNum) <= Number(allStorehouseMinNum)) {
          this.$message.error('仓库设置上限值必须比下限值大');
          return false;
        }
      }
      if (qalertStorehouseMode === '1') {
        if (!qalerts || !qalerts.length) {
          this.$message.error('请设置单个仓库数量预警');
          return false;
        }
        qalerts.forEach((item) => {
          if ((!item.upperLimit && item.upperLimit !== 0) || (!item.lowerLimit && item.lowerLimit !== 0)) {
            this.$message.error('请设置上限下限');
            canSave = false;
            return false;
          }
          if (!numReg.test(item.upperLimit) || !numReg.test(item.lowerLimit)) {
            this.$message.error('仓库设置上限下限输入错误');
            canSave = false;
            return false;
          }
          if (Number(item.upperLimit) <= Number(item.lowerLimit)) {
            this.$message.error('仓库设置上限值必须比下限值大');
            canSave = false;
            return false;
          }
        });
      }
      if (valertUsing === '1' && !valertDays && valertDays !== 0) {
        this.$message.error('请输入提前预警天数');
        return false;
      }
      if (valertUsing === '1' && valertDays && !numReg.test(valertDays)) {
        this.$message.error('提前预警天数输入错误');
        return false;
      }
      return canSave;
    },
    // 保存
    saveMateriel () {
      if (this.viewStatus) {
        // 查看
        this.closeDialog();
      } else {
        if (this.saving) {
          return false;
        }
        this.saving = true;
        this.$refs.popupObj.validate((valid) => {
          if (!valid) {
            this.$message.error('必填项不能为空');
            this.saving = false;
            return false;
          }
          if (!this.validData()) {
            this.saving = false;
            return false;
          }
          const params = this.dealParams();
          ManApi.saveMateriel(params).then((result) => {
            if (!result.status) {
              if (!this.popupObj.skuId) {
                // 新增
                result.obj.isNew = true;
              } else {
                result.obj.isNew = false;
              }
              this.$emit('submit', result.obj);
              this.closeDialog();
              this.$message({ message: '保存成功', type: 'success' });
              this.saving = false;
            } else {
              this.$message.error(result.comment || '保存失败');
              this.saving = false;
            }
          }).catch((error) => {
            this.saving = false;
            console.log(JSON.stringify(error));
            this.$message.error('网络不给力，请稍后再试');
          });
          return true;
        });
      }
    },
    // 弹层tab切换
    handlePopTab () {
      const tabShows = [false, false, false, false, false];
      tabShows[this.activeTabIndex] = true;
      this.tabShows = tabShows;
    },
    // 图片上传
    handlePicCardPreview (file) {
      this.showImageUrl = file.url;
      this.showImgDialog = true;
    },
    handlePicUploadSucc (status, file) {
      if (!this.popupObj.picRecords) {
        this.popupObj.picRecords = [];
      }
      this.popupObj.picRecords.push(file.url);
    },
    handlePicExceed () {
      this.$message.error('目前只允许上传一张图片，请与后台管理员联系');
    },
    handlePicRemove (file, fileList) {
      console.log(file, fileList);
    },
    // ========采购=========
    initVendor() {
      if (this.popupObj.usingSpyMgm === '1') {
        this.$set(this.popupObj, 'skuProcurementControls', [{ canEdit: true }]);
        this.skuProcurementControlsBC = [{ canEdit: true, fromAdd: true }];
      }
    },
    editVendor(index) {
      this.skuProcurementControlsBC[index] = Object.assign({}, this.popupObj.skuProcurementControls[index]);
      this.$set(this.popupObj.skuProcurementControls[index], 'canEdit', true);
    },
    addVendor(index) {
      if (this.popupObj.usingSpyMgm === '1') {
        this.popupObj.skuProcurementControls.splice((index + 1), 0, { canEdit: true });
        this.skuProcurementControlsBC.splice((index + 1), 0, { canEdit: true, fromAdd: true });
      }
    },
    deleteVendor(index) {
      this.popupObj.skuProcurementControls.splice(index, 1);
      this.skuProcurementControlsBC.splice(index, 1);
    },
    saveEditVendor(index) {
      this.popupObj.skuProcurementControls[index].canEdit = false;
    },
    cancelEditVendor(index) {
      const cache = Object.assign({}, this.skuProcurementControlsBC[index], { canEdit: false });
      if (cache.fromAdd) {
        this.popupObj.skuProcurementControls.splice(index, 1);
        this.skuProcurementControlsBC.splice(index, 1);
      } else {
        this.popupObj.skuProcurementControls.splice(index, 1, cache);
        this.popupObj.skuProcurementControls[index].canEdit = false;
      }
    },
    // ========数量预警=========
    initQalerts() {
      if (this.popupObj.qalertStorehouseMode === '1') {
        this.$set(this.popupObj, 'qalerts', [{ canEdit: true }]);
        this.qalertsBC = [{ canEdit: true, fromAdd: true }];
      }
    },
    editQalerts(index) {
      this.qalertsBC[index] = Object.assign({}, this.popupObj.qalerts[index]);
      this.$set(this.popupObj.qalerts[index], 'canEdit', true);
    },
    addQalerts(index) {
      if (this.popupObj.qalertStorehouseMode === '1') {
        this.popupObj.qalerts.splice((index + 1), 0, { canEdit: true });
        this.qalertsBC.splice((index + 1), 0, { canEdit: true, fromAdd: true });
      }
    },
    deleteQalerts(index) {
      this.popupObj.qalerts.splice(index, 1);
      this.qalertsBC.splice(index, 1);
    },
    saveEditQalerts(index) {
      this.popupObj.qalerts[index].canEdit = false;
    },
    cancelEditQalerts(index) {
      const cache = Object.assign({}, this.qalertsBC[index], { canEdit: false });
      if (cache.fromAdd) {
        this.popupObj.qalerts.splice(index, 1);
        this.qalertsBC.splice(index, 1);
      } else {
        this.popupObj.qalerts.splice(index, 1, cache);
        this.popupObj.qalerts[index].canEdit = false;
      }
    },
    // 初始获取一级部门 二级部门 员工列表
    loadEmployeeInfo(data) {
      // 一级部门
      ComApi.getOneLevelDept().then((oneLevelList) => {
        this.deptLevel1Select = [...oneLevelList];
        this.proDeptLevel1Select = [...oneLevelList];
      });
      // 二级部门
      ComApi.getTwoLevelDept({ oneLevelDept: data.deptLevel1 }).then((twoLevelList) => {
        this.deptLevel2Select = [...twoLevelList];
      });
      // 采购二级部门
      ComApi.getTwoLevelDept({ oneLevelDept: data.proDeptLevel1 }).then((twoLevelList) => {
        this.proDeptLevel2Select = [...twoLevelList];
      });
      // 采购员列表
      ComApi.getEmployees({
        deptLevel1: data.proDeptLevel1,
        deptLevel2: data.proDeptLevel2
      }).then((personList) => {
        this.procurerSelect = personList;
      });
    },
    // 需求一级部门改变
    changeOneLevelDept () {
      this.deptLevel2Select = [];
      this.$set(this.popupObj, 'deptLevel2', null);
      ComApi.getTwoLevelDept({ oneLevelDept: this.popupObj.deptLevel1 }).then((twoLevelList) => {
        this.deptLevel2Select = twoLevelList;
      });
    },
    // 采购一级部门改变
    changeProOneLevelDept () {
      this.proDeptLevel2Select = [];
      this.$set(this.popupObj, 'proDeptLevel2', null);
      ComApi.getTwoLevelDept({ oneLevelDept: this.popupObj.proDeptLevel1 }).then((twoLevelList) => {
        this.proDeptLevel2Select = twoLevelList;
      });
      this.changeProTwoLevelDept();
    },
    // 采购二级部门改变
    changeProTwoLevelDept () {
      ComApi.getEmployees({
        deptLevel1: this.popupObj.proDeptLevel1,
        deptLevel2: this.popupObj.proDeptLevel2
      }).then((personList) => {
        this.procurerSelect = personList;
        this.popupObj.procurers = [];
      });
    },
    // 处理CheckBox显示
    dealRender (newData) {
      const checkBoxArr = [
        'isCriticalPart', 'isSparePart',
        'inspectingMaterial', 'inspectingProcess',
        'inspectingProduct', 'allowingProcurement',
        'allowingOutsourcing', 'allowingProduction',
        'allowingSales', 'batchNumUsing',
        'seqNumUsing', 'validitySpanUsing',
        'bomManagementUsing', 'qalertUsing',
        'valertUsing', 'usingSpyMgm'
      ];
      checkBoxArr.forEach((item) => {
        if (newData[item] === '1') {
          this.$set(this.popupObj, item, '1');
        } else {
          this.$set(this.popupObj, item, '0');
        }
      });
    }
  },
  created () {
    ComApi.getBasicConfigs().then((result) => {
      this.cateGorySelect = result.skuTypes;
      this.propertySelect = result.skuPropertys;
      this.skuGradeSelect = result.skuLevels;
      this.manufacturerSelect = result.manufacturers;
      this.skuUnitSelect = result.basicUnits;
      this.currencySelect = result.currency;
      this.allowOverSelect = result.allowingOverissuance;
    });
    // 仓库列表
    ComApi.getStores().then((storeList) => {
      this.storeSelect = storeList;
    });
    // 供应商列表
    ComApi.getSupplys().then((vendorList) => {
      this.vendorSelect = vendorList;
    });
    // 员工列表
    ComApi.getEmployees().then((personList) => {
      this.createUserSelect = personList;
    });
  },
  watch: {
    parentData (newData, oldData) {
      if (newData !== oldData) {
        this.popupObj = newData;
        this.dealDetail(newData);
        // this.initUploadImag(this.popupObj.picList);
        this.skuProcurementControlsBC = newData.skuProcurementControls ? newData.skuProcurementControls.slice() : [];
        this.qalertsBC = newData.qalerts ? newData.qalerts.slice() : [];
        this.loadEmployeeInfo(newData);
        // 避免初始显示表单校验结果
        setTimeout(() => {
          this.clearValidate();
        }, 10);
        // 显示第一个标签页
        this.activeTabIndex = '0';
        this.tabShows = [true, false, false, false, false];
        // 处理CheckBox显示
        this.dealRender(newData);
        // 创建人默认为当前用户
        if (!this.popupObj.skuId) {
          this.$set(this.popupObj, 'createUser', this.employeeId);
        }
      }
    },
    // 基本单位
    'popupObj.skuUnit': function skuUnit(val) {
      if (!this.popupObj.skuId) {
        this.$set(this.popupObj, 'inventoryUnit', val);
      }
    },
    // 库存单位
    'popupObj.inventoryUnit': function inventoryUnit(val) {
      if (val === this.popupObj.skuUnit) {
        this.$set(this.popupObj, 'inventoryUnitRate', 1);
      } else {
        this.$set(this.popupObj, 'inventoryUnitRate', null);
      }
    },
    // 批号管理
    'popupObj.batchNumUsing': function batchNumUsing(val) {
      if (val === '0') {
        this.$set(this.popupObj, 'batchNumFlag', null);
      }
    },
    // 序列号管理
    'popupObj.seqNumUsing': function seqNumUsing(val) {
      if (val === '0') {
        this.$set(this.popupObj, 'seqNumFlag', null);
      }
    },
    // 保质期管理
    'popupObj.validitySpanUsing': function validitySpanUsing(val) {
      if (val === '0') {
        this.$set(this.popupObj, 'validitySpan', null);
        this.$set(this.popupObj, 'validitySpanUnit', null);
      }
    },
    // BOM版本管理
    'popupObj.bomManagementUsing': function bomManagementUsing(val) {
      if (val === '0') {
        this.$set(this.popupObj, 'bomManagementFlag', null);
      }
    },
    'popupObj.qalertUsing': function qalertUsing(val) {
      if (val === '0') {
        this.$set(this.popupObj, 'qalertStorehouseMode', null);
      }
    },
    // 数量预警模式
    'popupObj.qalertStorehouseMode': function qalertStorehouseMode(val) {
      if (val === '1') {
        this.$set(this.popupObj, 'allStorehouseMaxNum', null);
        this.$set(this.popupObj, 'allStorehouseMinNum', null);
      } else if (val === '0') {
        this.$set(this.popupObj, 'qalerts', []);
        this.qalertsBC = [];
      }
    },
    'popupObj.valertUsing': function qalertStorehouseMode(val) {
      if (val === '0') {
        this.$set(this.popupObj, 'valertDays', null);
      }
    },
    'popupObj.usingSpyMgm': function usingSpyMgm(val) {
      if (val === '0') {
        this.$set(this.popupObj, 'skuProcurementControls', []);
        this.skuProcurementControlsBC = [];
      }
    }
  },
};
</script>

<style lang="sass">
$SEARCHHEIGHT: 56px
$PAGEHEIGHT: 56px
.cp-manage-materiel-popup
  .el-table
    th, td
      text-align: center
  .ml-dialog
    &::-webkit-scrollbar
      display: none
    .el-dialog
      margin-top: 5vh!important
    .el-dialog__body
      padding: 8px 32px 12px 12px
    .el-dialog__footer
      text-align: center
      padding-top: 0
      .el-button
        width: 80px
    .dialog-footer
      text-align: center
      margin-top: 10px
    p.tip-info
      text-align: left
      margin-top: 5px
    .el-tabs__item:focus.is-active.is-focus:not(:active)
      box-shadow: none
    .el-tabs__nav-wrap::after
      background-color: white
    .dg-tabs
      position: relative
      height: 40px
      background: white
      padding-left: 20px
  .c-pop-tab
    position: relative
    padding: 16px 0 0 20px
  .ml-pop-form
    .el-form-item
      width: 100%
      margin-right: 0
    .el-form-item__label
      text-align: left
    .el-select
      width: 100%
    .el-form-item__content
      width: calc(100% - 100px)
  .ml-upload-img
    position: relative
    width: 100%
    height: 86px
    margin-bottom: 15px
    .upload-block
      position: absolute
      left: 40px
      right: 0
      top: 0
      bottom: 0
      overflow-x: auto
      overflow-y: hidden
      .el-upload--picture-card
        width: 86px
        height: 86px
        line-height: 88px
        text-align: center
        background-color: white
        border: 1px solid #dcdfe6
      .el-upload-list__item
        width: 86px
        height: 86px
  .ml-view-table
    width: 100%
    table
      width: 100%!important
      &::before
        display: none
      .icon-act
        font-size: 16px
        margin-left: 3px
        margin-right: 3px
      th.gutter
        display: table-cell!important
    .el-table__empty-block
      display: none
    .append-content
      text-align: center
      margin: 8px auto
  .ml-register, .ml-aftersale, .ml-check, .ml-control
    .ml-pop-title
      margin: 12px 0 8px 0
    .ml-p
      margin-bottom: 8px
  .ml-pop-content
    padding-left: 32px
    white-space: nowrap
  .tab-base
    .bs-title
      margin-bottom: 8px
    .custom-category
      .el-input
        width: calc(100% - 60px)
      .el-button
        width: 60px
  .tab-store
    .c-store-title
      margin-bottom: 8px
    .c-store-content
      position: relative
      padding: 0 16px 0 32px
    .cwa-content
      .el-row
        margin-top: 10px
      .height32
        height: 32px
        line-height: 32px
      .v-alert-day
        width: 100px
        margin-left: 10px
  .tab-purchase
    .c-purchase-title
      margin-bottom: 8px
    .c-purchase-content
      position: relative
      padding: 0 16px 0 32px
  .tab-sales
    .c-sales-content
      position: relative
      padding: 0 16px 0 32px
  .tab-prod
    .c-prod-content
      position: relative
      padding: 0 16px 0 32px
  .init-btn
    padding: 8px 0 0 56px
  .init-link a
    padding-left: 20px
    color: #409EFF
    font-weight: 600
  .icon-act
    font-size: 16px
    font-weight: 500
    cursor: pointer
    margin-left: 3px
    margin-right: 3px
    &:hover
      color: #5D9BFB
  .el-checkbox
    height: 24px
    line-height: 24px
</style>
